using System;
using System.Collections.Generic;
using System.Collections;
using System.Diagnostics;
using System.Timers;
using System.Text;
using System.Net;
using System.Net.Sockets;
using System.Threading;
using AsyncSockets;
using AsyncSockets.AsyncSocketServer;


namespace DataServiceCenter
{
    public class ServiceCenter
    {
        //添加
        int m_numConnections;//系统最大容量
        //int m_port;
        string m_addressFamily;//使用地址族
        int m_bufferSize;//输入缓冲区大小
        const int opsToPreAlloc = 1;
        DtuArgsBufferManager m_dtuArgsBufferManager;
        private Object m_resuePoolLock = new Object();

        bool m_isListing;
        private long m_numOnLine = 0;//连接数计数
        private readonly Dictionary<string, DtuArgs> m_hsableInneridToDtu;//Dtu与ID映射表
        private readonly Dictionary<string, string> m_hsableIDToInnerid;//DtuID与内部ID映射表
        private int m_interval;//超时值
        private TransportMode m_mode;//数据包模式
        //private readonly object objectForLock = new object();
        //private readonly System.Timers.Timer IsTimeOutTimer;//刷新定时器
        private readonly System.Threading.Timer m_isTimeOutTimer;
        private AsyncServer server;//DSCServer 服务器

        ReuseDtuArgsPool m_reuseDtuPool;
        //添加功能
        //int numConnections;
        //int receiveSize;
        IPEndPoint localEndPoint;
        //int port;

        public event EventHandler<DtuArgs> OnClientDisconnected;//客户端断开连接事件

        public event EventHandler<DtuArgs> OnClientConnected;//客户端连接事件

        public event EventHandler<DtuArgs> OnDataIn;//接收到数据事件        
        public bool IsListing
        {
            get { return m_isListing; }
        }

        public long NumConnectedSockets
        {
            get
            {
                //return server.NumConnectedSockets;//一连接为准
                return Interlocked.Read(ref m_numOnLine);//以注册过为准
            }
        }

        public ServiceCenter(int numConnections, int bufferSize, string addressFamily, int port, int interval, TransportMode mode)//端口 刷新间隔 数据模式
        {
            m_isListing = false;
            m_numConnections = numConnections;
            //m_port = port;
            m_addressFamily = addressFamily.ToLower();
            m_bufferSize = bufferSize;
            m_mode = mode;//数据模式
            m_interval = interval;//刷新时间间隔
            m_isTimeOutTimer = new System.Threading.Timer(new TimerCallback(IsTimeOutTimer_Elapsed), null, Timeout.Infinite, m_interval * 100);//刷新定时器
            //this.IsTimeOutTimer = new System.Timers.Timer(20000.0);      
            //this.IsTimeOutTimer.SynchronizingObject = null;//参数对象
            //this.IsTimeOutTimer.Elapsed += new System.Timers.ElapsedEventHandler(this.IsTimeOutTimer_Elapsed);//注册刷新事件

            m_numOnLine = 0;//连接计数器
            m_dtuArgsBufferManager = new DtuArgsBufferManager(bufferSize * numConnections * opsToPreAlloc,
                bufferSize);

            m_dtuArgsBufferManager.InitBuffer();
            m_hsableInneridToDtu = new Dictionary<string, DtuArgs>();//ID Dtu 映射表
            m_hsableIDToInnerid = new Dictionary<string, string>();//id 内部id 映射表
            m_reuseDtuPool = new ReuseDtuArgsPool(numConnections);
            DtuArgs dtuArgs;
            for (int i = 0; i < numConnections; i++)
            {
                dtuArgs = new DtuArgs();
                m_dtuArgsBufferManager.SetBuffer(dtuArgs);
                m_reuseDtuPool.Push(dtuArgs);

            }
            // 支持两种地址族类型: ipv4 和 ipv6 
            if (addressFamily.ToLower().Equals("ipv4"))
            {
                localEndPoint = new IPEndPoint(IPAddress.Any, port);
            }
            else if (addressFamily.ToLower().Equals("ipv6"))
            {
                localEndPoint = new IPEndPoint(IPAddress.IPv6Any, port);
            }
            else
            {
                throw new ArgumentException("被指定的地址族无效");
            }

            //this.server = new DSCServer(m_numConnections, m_receiveSize);//创建DSCServer对象(基础层通讯服务器)
            server = new AsyncServer(m_numConnections, m_bufferSize);
            this.server.OnDataIn += new EventHandler<AsyncUserToken>(this.svr_OnDataIn);//注册接收到数据事件
            this.server.OnDisconnected += new EventHandler<AsyncUserToken>(this.svr_OnDisconnected);//注册断开连接事件

            this.server.OnError += new EventHandler<AsyncSocketErrorEventArgs>(svr_OnError);//处理Socket错误

        }

        public void Start()
        {
            //server = new DSCServer(m_numConnections, m_receiveSize);
            server.Init();
            try
            {
                server.Start(localEndPoint);//启动服务器
                m_isListing = true;
                this.m_isTimeOutTimer.Change(m_interval * 100, m_interval * 100);//启动超时监控定时器
            }
            catch (AsyncSocketException asyncSocketException)
            {
                m_isListing = false;
                throw asyncSocketException;//启动失败
            }

            //this.IsTimeOutTimer.Start();

        }

        public bool Disconnect(string id)
        {
            id = id.Trim();
            string connectionId;
            if (!TryIdToInnerid(id, out connectionId))
            {
                return false;
            }
            try
            {
                try
                {
                    this.server.Disconnect(connectionId);
                    return true;
                }
                catch (AsyncSocketException asyncSocketException)
                {
                    throw asyncSocketException;
                }

            }
            catch
            {
                return false;
            }

        }



        private bool TryIdToInnerid(string id, out string innerId)//Dtu ID 映射为 内部Socket ID(-1 返回失败)
        {
            //string innerId;
            lock (((ICollection)m_hsableIDToInnerid).SyncRoot)
            {
                if (!this.m_hsableIDToInnerid.TryGetValue(id, out innerId))
                {
                    return false;
                }
                else
                {
                    return true;
                }
            }

        }

        private bool TryInneridToId(string innerId, out DtuArgs dtuData)//内部ID转换为 Dtu ID
        {
            lock (((ICollection)m_hsableInneridToDtu).SyncRoot)
            {
                //DtuData dtuData;
                if (!this.m_hsableInneridToDtu.TryGetValue(innerId, out dtuData))
                {
                    return false;
                }
                else
                {
                    return true;
                }
            }
        }
        private bool IsHeart(DtuArgs dtuArgs)
        {
            if (this.m_mode == TransportMode.小数据包模式)
            {
                return ((dtuArgs.BytesReceived == 1) && (Convert.ToInt32(dtuArgs.ReceiveBuffer[dtuArgs.Offset]) == 0xfe));
            }
            else
            {
                return (((((dtuArgs.BytesReceived == 5) && (Convert.ToInt32(dtuArgs.ReceiveBuffer[dtuArgs.Offset]) == 2)) && ((Convert.ToInt32(dtuArgs.DataBuffer[dtuArgs.Offset + 1]) == 1) && (Convert.ToInt32(dtuArgs.DataBuffer[dtuArgs.Offset + 2]) == 0))) && (Convert.ToInt32(dtuArgs.DataBuffer[dtuArgs.Offset + 3]) == 0xfe)) && (Convert.ToInt32(dtuArgs.DataBuffer[dtuArgs.Offset + 4]) == 3));
            }
        }


        private bool IsHeart(byte[] s)
        {
            if (this.m_mode == TransportMode.小数据包模式)
            {
                return ((s.Length == 1) && (Convert.ToInt32(s[0]) == 0xfe));
            }
            else
            {
                return (((((s.Length == 5) && (Convert.ToInt32(s[0]) == 2)) && ((Convert.ToInt32(s[1]) == 1) && (Convert.ToInt32(s[2]) == 0))) && (Convert.ToInt32(s[3]) == 0xfe)) && (Convert.ToInt32(s[4]) == 3));
            }
        }

        private bool IsEndSymbol(DtuArgs dtuArgs)
        {
            if (Convert.ToInt32(dtuArgs.ReceiveBuffer[dtuArgs.Offset + 3]) == 0x4d)
            {
                return false;
            }
            else
            {
                return true;
            }
        }


        private bool IsEndSymbol(byte[] data)
        {
            if (Convert.ToInt32(data[3]) == 0x4d)
            {
                return false;
            }
            else
            {
                return true;
            }
        }

        private bool IsRegisterPacket(DtuArgs dtuArgs)
        {
            int i;
            int num;
            if (dtuArgs.BytesReceived != 0x15)//注册包长度21
            {
                return false;
            }
            for (i = 0; i < 4; i++)//前四位Dtu ID 字段
            {
                num = Convert.ToInt32(dtuArgs.ReceiveBuffer[dtuArgs.Offset + i]);
                if ((num < 0) || (num > 0xff))//异常数据
                {
                    return false;
                }
            }
            for (i = 0x10; i < 20; i++)//后四位IP 地址字段
            {
                num = Convert.ToInt32(dtuArgs.ReceiveBuffer[dtuArgs.Offset + i]);
                if ((num < 0) || (num > 0xff))//异常数据
                {
                    return false;
                }
            }
            for (i = 4; i < 15; i++)//中间11位 电话号码字段
            {
                num = Convert.ToInt32(dtuArgs.ReceiveBuffer[dtuArgs.Offset + i]);
                if ((num < 0x30) || (num > 0x39))
                {
                    return false;
                }
            }
            return true;
        }

        private bool IsRegisterPacket(byte[] dataBytes)
        {
            int i;
            int num;
            if (dataBytes.Length != 0x15)//注册包长度21
            {
                return false;
            }
            for (i = 0; i < 4; i++)//前四位Dtu ID 字段
            {
                num = Convert.ToInt32(dataBytes[i]);
                if ((num < 0) || (num > 0xff))//异常数据
                {
                    return false;
                }
            }
            for (i = 0x10; i < 20; i++)//后四位IP 地址字段
            {
                num = Convert.ToInt32(dataBytes[i]);
                if ((num < 0) || (num > 0xff))//异常数据
                {
                    return false;
                }
            }
            for (i = 4; i < 15; i++)//中间11位 电话号码字段
            {
                num = Convert.ToInt32(dataBytes[i]);
                if ((num < 0x30) || (num > 0x39))
                {
                    return false;
                }
            }
            return true;
        }

        //private void IsTimeOutTimer_Elapsed(object sender,System.Timers.ElapsedEventArgs e)
        private void IsTimeOutTimer_Elapsed(object o)
        {
            Debug.WriteLine("timer_Tick 1");
            try
            {
                lock (((ICollection)m_hsableInneridToDtu).SyncRoot)
                {
                    if (m_mode != TransportMode.全透明模式)
                    {
                        foreach (string connectionid in this.m_hsableInneridToDtu.Keys)
                        {
                            DtuArgs dtuArgs = this.m_hsableInneridToDtu[connectionid];

                            Debug.WriteLine(string.Format("timer_Tick 2:<{0},{1}>", connectionid, dtuArgs.ID));

                            if (dtuArgs.IsOnline)
                            {
                                TimeSpan span = (TimeSpan)(DateTime.Now - dtuArgs.RefreshTime);
                                Debug.WriteLine(string.Format("timer_Tick 3:<{0},{1},{2},{3}>", new object[] { connectionid, dtuArgs.ID, span.TotalSeconds, this.m_interval }));

                                if (span.TotalSeconds >= this.m_interval)//已经超时
                                {
                                    dtuArgs.IsOnline = false;

                                    Interlocked.Decrement(ref this.m_numOnLine);

                                    EventHandler<DtuArgs> handler = OnClientDisconnected;
                                    // 如果订户事件将为空(null)
                                    if (handler != null)
                                    {
                                        Debug.WriteLine("timer_Tick 4");
                                        handler(this, dtuArgs);//抛出Dtu掉线事件
                                    }
                                }
                            }
                        }
                    }
                    else// 全透明模式
                    {
                        foreach (string innerid in this.m_hsableInneridToDtu.Keys)
                        {
                            DtuArgs dtuArgs = this.m_hsableInneridToDtu[innerid];

                            Debug.WriteLine(string.Format("timer_Tick 2:<{0},{1}>", innerid, dtuArgs.ID));

                            if (dtuArgs.IsOnline)
                            {
                                TimeSpan span = (TimeSpan)(DateTime.Now - dtuArgs.RefreshTime);
                                Debug.WriteLine(string.Format("timer_Tick 3:<{0},{1},{2},{3}>", new object[] { innerid, dtuArgs.ID, span.TotalSeconds, this.m_interval }));

                                if (span.TotalSeconds >= this.m_interval)//已经超时
                                {
                                    //dtuArgs.IsOnline = false;

                                    //Interlocked.Decrement(ref this.m_numOnLine);

                                    //EventHandler<ServiceEventArgs> handler = OnClientDisconnected;
                                    //// 如果订户事件将为空(null)
                                    //if (handler != null)
                                    //{
                                    //    Debug.WriteLine("timer_Tick 4");
                                    //    handler(this, new ServiceEventArgs(dtuArgs));//抛出Dtu掉线事件
                                    //}


                                    //lock (((ICollection)m_hsableIDToInnerid).SyncRoot)
                                    //{
                                    //    this.m_hsableIDToInnerid.Remove(dtuArgs.ID);
                                    //}
                                    //FreeResueDtuArgs(dtuArgs);
                                    //lock (((ICollection)m_hsableInneridToDtu).SyncRoot)
                                    //{
                                    //    this.m_hsableInneridToDtu.Remove(connectionId);
                                    //}

                                    try
                                    {
                                        this.server.Disconnect(innerid);
                                    }
                                    catch (AsyncSocketException asyncSocketException)
                                    {
                                        //FreeResueDtuArgs(dtuArgs);
                                        throw asyncSocketException;
                                        //return;
                                    }
                                }
                            }
                        }
                    }

                }
            }
            catch (Exception exception_debug)
            {
                Debug.WriteLine("timer_Tick 5 " + exception_debug.Message);
            }
        }

        public bool Send(string id, byte[] dataBytes)
        {
            id = id.Trim();
            string connectionId;
            if (!TryIdToInnerid(id, out connectionId))
            {
                return false;
            }
            try
            {
                try
                {
                    this.server.Send(connectionId, CodeConverter.ConverBytesToDtuFormat(dataBytes));
                    return true;//发送成功                    
                }
                catch (AsyncSocketException asyncSocketException)
                {
                    throw asyncSocketException;
                }
            }
            catch
            {
                return false;//发送失败
            }
        }



        public void Stop()//停止服务器
        {
            m_isListing = false;
            //this.m_hsableInneridToDtu.Clear();
            //this.m_hsableIDToInnerid.Clear();
            this.m_isTimeOutTimer.Change(Timeout.Infinite, m_interval * 100);
            //this.IsTimeOutTimer.Stop();
            this.server.Shutdown();
        }

        private void svr_OnDataIn(object sender, AsyncUserToken token)
        {
            bool isRegistered;//是否存在Dtu
            DtuArgs dtuArgs;
            //object obj2;
            Debug.WriteLine("svr_OnDataIn 1");
            string connectionId = token.ConnectionId;
            //复制接收到的数据
            //byte[] receiveBytes = new byte[token.BytesReceived];
            //Array.Copy(token.ReceiveBuffer, token.Offset, receiveBytes, 0, token.BytesReceived);

            DateTime now = DateTime.Now;
            lock (((ICollection)m_hsableInneridToDtu).SyncRoot)
            {
                isRegistered = this.m_hsableInneridToDtu.TryGetValue(connectionId, out dtuArgs);
            }
            if (isRegistered)//发送过注册包
            {
                Debug.WriteLine("svr_OnDataIn 2");

                Array.Copy(token.ReceiveBuffer, token.Offset, dtuArgs.ReceiveBuffer, dtuArgs.Offset, token.BytesReceived);
                dtuArgs.SetBytesReceived(token.BytesReceived);

                dtuArgs.RefreshTime = now;//更新刷新时间
                if (!dtuArgs.IsOnline)//原来状态为下线
                {
                    Debug.WriteLine("svr_OnDataIn 3");
                    dtuArgs.IsOnline = true;//设为在线
                    Interlocked.Increment(ref this.m_numOnLine);
                    if (this.OnClientConnected != null)
                    {
                        Debug.WriteLine("svr_OnDataIn 4");
                        this.OnClientConnected(this, dtuArgs);//上线
                    }
                }

                //if (this._mode == Mode.全透明模式)
                switch (this.m_mode)
                {
                    case TransportMode.全透明模式:
                        {
                            Debug.WriteLine("svr_OnDataIn 5");
                            //dtuArgs.ReceiveBuffer = new byte[receiveBytes.Length];


                            //Array.Copy(token.ReceiveBuffer, token.Offset,dtuArgs.ReceiveBuffer,dtuArgs.Offset, token.BytesReceived);
                            //dtuArgs.SetBytesReceived(token.BytesReceived);

                            EventHandler<DtuArgs> handler = OnDataIn;
                            // 如果订户事件将为空(null)
                            if (handler != null)
                            {
                                handler(this, dtuArgs);//收到数据
                            }
                            break;
                        }
                    case TransportMode.小数据包模式:
                        {
                            if (!this.IsHeart(dtuArgs))
                            {
                                Debug.WriteLine("svr_OnDataIn 7");
                                byte[] bytesDecoded = CodeConverter.DecodeBytes(dtuArgs);

                                Array.Copy(bytesDecoded, 0, dtuArgs.ReceiveBuffer, dtuArgs.Offset, bytesDecoded.Length);
                                dtuArgs.SetBytesReceived(bytesDecoded.Length);

                                EventHandler<DtuArgs> handler = OnDataIn;
                                // 如果订户事件将为空(null)
                                if (handler != null)
                                {
                                    Debug.WriteLine("svr_OnDataIn 8");
                                    handler(this, dtuArgs);//收到数据
                                }
                            }
                            else//心跳包过滤掉
                            {
                                Debug.WriteLine("svr_OnDataIn 6");
                            }
                            break;
                        }
                    case TransportMode.大数据包模式:
                        {
                            if (!this.IsHeart(dtuArgs))
                            {
                                Debug.WriteLine("svr_OnDataIn 9");
                                //合并多包数据
                                dtuArgs.DataBuffer = CodeConverter.ByteAdd(dtuArgs.DataBuffer, CodeConverter.GetBigData(dtuArgs));
                                if (this.IsEndSymbol(dtuArgs))//多包结束
                                {
                                    Debug.WriteLine("svr_OnDataIn 10");
                                    //dtuArgs.ReceiveBuffer = dtuArgs.DataBuffer;
                                    Array.Copy(dtuArgs.DataBuffer, 0, dtuArgs.ReceiveBuffer, dtuArgs.Offset, dtuArgs.DataBuffer.Length);
                                    dtuArgs.SetBytesReceived(dtuArgs.DataBuffer.Length);

                                    EventHandler<DtuArgs> handler = OnDataIn;
                                    // 如果订户事件将为空(null)
                                    if (handler != null)
                                    {
                                        handler(this, dtuArgs);//收到数据                                                                           
                                    }
                                    dtuArgs.DataBuffer = new byte[0];//
                                    //dtuArgs.DataBuffer = null;//清除缓冲区
                                }
                            }
                            else
                            {
                                Debug.WriteLine("svr_OnDataIn 6");
                            }
                            break;
                        }
                }
            }
            else//不在Dtu哈希表中
            {
                Debug.WriteLine("svr_OnDataIn 11");

                lock (m_resuePoolLock)
                {
                    dtuArgs = m_reuseDtuPool.Pop();
                }

                Array.Copy(token.ReceiveBuffer, token.Offset, dtuArgs.ReceiveBuffer, dtuArgs.Offset, token.BytesReceived);
                dtuArgs.SetBytesReceived(token.BytesReceived);

                if (this.m_mode == TransportMode.全透明模式)
                {
                    Debug.WriteLine("svr_OnDataIn 12");
                    //lock (this.m_resuePoolLock)
                    //{
                    //    dtuArgs = m_reuseDtuPool.Pop();
                    //}

                    //int dtuid = _hsable_id_innerid.Keys + 1;//     

                    //dtudata.ID = dtuid.ToString().PadLeft(8, '0');
                    dtuArgs.ID = Guid.NewGuid().ToString("N");
                    //使用实际地址
                    dtuArgs.IP = token.EndPoint.Address.ToString();
                    //dtuData.IP = "0.0.0.0";
                    dtuArgs.PhoneNumber = "00000000000";
                    //dtuArgs.ReceiveBuffer = receiveBytes;

                    //Array.Copy(token.ReceiveBuffer,token.Offset,dtuArgs.ReceiveBuffer,dtuArgs.Offset, token.BytesReceived);
                    //dtuArgs.SetBytesReceived(token.BytesReceived);

                    dtuArgs.LoginTime = now;
                    dtuArgs.RefreshTime = now;
                    dtuArgs.IsOnline = true;//设为在线                    

                    lock (((ICollection)m_hsableInneridToDtu).SyncRoot)
                    {
                        this.m_hsableInneridToDtu.Add(connectionId, dtuArgs);//加入到Dtu 哈希表中
                    }
                    lock (((ICollection)m_hsableIDToInnerid).SyncRoot)
                    {
                        this.m_hsableIDToInnerid.Add(dtuArgs.ID, connectionId);
                    }

                    Interlocked.Increment(ref this.m_numOnLine);//增加连接数

                    EventHandler<DtuArgs> handler = OnClientConnected;
                    // 如果订户事件将为空(null)
                    if (handler != null)
                    {
                        handler(this, dtuArgs);//连接上
                    }

                    handler = OnDataIn;
                    if (handler != null)
                    {
                        handler(this, dtuArgs);//接收到数据
                    }
                }
                else//其他模式
                {
                    Debug.WriteLine("svr_OnDataIn 13");


                    if (this.IsRegisterPacket(dtuArgs))//注册包
                    {
                        Debug.WriteLine("svr_OnDataIn 14");
                        string id = CodeConverter.GetDtuID(dtuArgs);
                        string innerid;
                        bool IsOnline;

                        lock (((ICollection)m_hsableIDToInnerid).SyncRoot)
                        {
                            IsOnline = this.m_hsableIDToInnerid.TryGetValue(id, out innerid);
                        }
                        //if (this.m_hsableIDToInnerid.TryGetValue(id, out innerid))
                        if (IsOnline)
                        {
                            //isRegistered = this.m_hsableIdToInnerid.TryGetValue(id, out innerid);
                            //}

                            //if (isRegistered)
                            //{

                            //lock (((ICollection)m_hsableInneridToDtu).SyncRoot)
                            //{
                            //    if (m_hsableInneridToDtu.ContainsKey(innerid))
                            //    {
                            //        FreeResueDtuArgs(m_hsableInneridToDtu[innerid]);
                            //        this.m_hsableInneridToDtu.Remove(innerid);
                            //    }
                            //}
                            //lock (((ICollection)m_hsableIdToInnerid).SyncRoot)
                            //{
                            //try
                            //{  
                            //this.m_hsableIDToInnerid.Remove(id);
                            //}
                            //catch (Exception exception)
                            //{
                            //    FreeResueDtuArgs(dtuArgs);
                            //    throw exception;
                            //}
                            //}

                            try
                            {
                                this.server.Disconnect(innerid);
                            }
                            catch (AsyncSocketException asyncSocketException)
                            {
                                FreeResueDtuArgs(dtuArgs);
                                throw asyncSocketException;
                                //return;
                            }
                        }


                        //string phonenumber = 

                        //string ip = "";
                        //for (int i = 0x10; i < 20; i++)
                        //{
                        //    ip = ip + Convert.ToInt32(receiveBytes[i]).ToString() + ".";
                        //}

                        //ip = ip.Substring(0, ip.Length - 1);

                        dtuArgs.ID = id;
                        dtuArgs.LoginTime = now;
                        dtuArgs.RefreshTime = now;
                        // 使用实际地址    
                        dtuArgs.IP = token.EndPoint.Address.ToString();
                        //dtuData.IP = ip;//使用注册地址
                        dtuArgs.PhoneNumber = Encoding.Default.GetString(dtuArgs.ReceiveBuffer, dtuArgs.Offset + 4, dtuArgs.Offset + 11);
                        dtuArgs.IsOnline = true;

                        lock (((ICollection)m_hsableInneridToDtu).SyncRoot)
                        {
                            this.m_hsableInneridToDtu.Add(connectionId, dtuArgs);
                        }
                        lock (((ICollection)m_hsableIDToInnerid).SyncRoot)
                        {
                            this.m_hsableIDToInnerid.Add(id, connectionId);
                        }


                        Interlocked.Increment(ref this.m_numOnLine);

                        EventHandler<DtuArgs> handler = OnClientConnected;
                        // 如果订户事件将为空(null)
                        if (handler != null)
                        {
                            Debug.WriteLine("svr_OnDataIn 15");
                            handler(this, dtuArgs);//上线
                        }


                    }
                    else//异常 没有注册过且不是全透明模式发送非法数据
                    {
                        Debug.WriteLine("svr_OnDataIn 16");
                        try
                        {
                            this.server.Disconnect(connectionId);
                        }
                        catch (AsyncSocketException asyncSocketException)
                        {
                            throw asyncSocketException;
                        }
                    }
                }
            }
        }

        private void svr_OnError(object sender, AsyncSocketErrorEventArgs token)
        {
            if (sender != null)//服务器错误
            {

            }
            else//客户端错误
            {
                //AsyncUserToken token=(AsyncUserToken)sender;
            }
        }

        private void FreeResueDtuArgs(DtuArgs dtuArgs)
        {
            dtuArgs.IsOnline = false;
            dtuArgs.ClientSocket = null;
            //dtuArgs.DataBuffer = null;
            //dtuArgs.ReceiveBuffer = null;
            dtuArgs.SetBytesReceived(0);

            dtuArgs.ID = null;
            dtuArgs.IP = null;
            //dtuArgs.LoginTime = null;
            dtuArgs.PhoneNumber = null;
            //dtuArgs.RefreshTime = null;
            m_reuseDtuPool.Push(dtuArgs);
        }
        private void svr_OnDisconnected(object sender, AsyncUserToken token)
        {
            bool isRegistered;// 是否注册过Dtu
            string connectionId = token.ConnectionId;
            DtuArgs dtuArgs;
            lock (((ICollection)m_hsableInneridToDtu).SyncRoot)
            {
                isRegistered = this.m_hsableInneridToDtu.TryGetValue(connectionId, out dtuArgs);// 发送过注册包
            }
            if (isRegistered)// 发送过注册包
            {
                if (dtuArgs.IsOnline)
                {
                    Interlocked.Decrement(ref this.m_numOnLine);

                    EventHandler<DtuArgs> handler = OnClientDisconnected;
                    // 如果订户事件将为空(null)
                    if (handler != null)
                    {
                        Debug.WriteLine("svr_OnDisconnected 4");
                        handler(this, dtuArgs);//抛出掉线事件
                    }
                }
                lock (((ICollection)m_hsableIDToInnerid).SyncRoot)
                {
                    this.m_hsableIDToInnerid.Remove(dtuArgs.ID);
                }
                FreeResueDtuArgs(dtuArgs);
                lock (((ICollection)m_hsableInneridToDtu).SyncRoot)
                {
                    this.m_hsableInneridToDtu.Remove(connectionId);
                }
            }
            else
            {
                Debug.WriteLine("Bug");
            }

        }



        //public delegate void DSCEventHandler(object sender, DSCEventArgs e);

        //public delegate void DSCEventN();
    }
}

